/**
 * 用于云平台的业务统一管理
 * 
 */
import AV from "leancloud-storage"

AV.init({
  appId: "yNrjxScMjPM6nTugOncH7hYz-gzGzoHsz",
  appKey: "r56DgFKFGHuzgmXnCmrhPm3i",
  serverURL: "https://ynrjxscm.lc-cn-n1-shared.com"
});

// 用户相关
const Auth = {
  // 注册
  register(username,password){
    var user = new AV.User();
    user.setUsername(username);
    user.setPassword(password);
    return new Promise((resolve,reject)=>{
      user.signUp().then((loginedUser)=>{
        console.log("成功",loginedUser)
        resolve(loginedUser)
      }, ((error)=>{
        console.log("失败",error)
        reject(error)
      }));
    })
  },
  // 登录
  login(username,password){
    return new Promise((resolve,reject)=>{
      AV.User.logIn(username, password).then((loginedUser)=>{
        resolve(loginedUser)
      },(error)=>{
        reject(error)
      });
    })
  },
  // 注销
  logout(){
    AV.User.logOut();
  },
  // 当前用户
  getCurrentUser(){
    return AV.User.current();
  }
}

// 上传图片
const Uploader = {
  // 上传图片
  add(file,filename){
    const item = new AV.Object("Image");
    const avFile = new AV.File(filename,file)
    item.set("filename",filename)
    item.set('owner',AV.User.current())
    item.set("url",avFile)
    return new Promise((resolve,reject)=>{
      item.save().then((serveFile)=>{
        resolve(serveFile)
      },(error)=>{
        reject(error)
      })
    })
  },
  // 查询图片
  find(page=0,limit=10){
    const query = new AV.Query("Image");
    query.include("owner")
    query.limit(limit)
    query.skip(page*limit)
    query.equalTo('owner',AV.User.current())
    return new Promise((resolve,reject)=>{
      query.find().then((response)=>{
        console.log('查询成功',response)
        resolve(response)
      }).catch((error)=>{
        console.log("查询失败",error)
        reject(error)
      })
    })
  }



}


export {Auth,Uploader}